<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="72px"
			class="queryForms">
			<el-form-item label="计划名称" prop="scheduleName">
				<el-input v-model="queryParams.scheduleName" placeholder="请输入计划名称" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="审批状态" prop="approvalState">
				<el-select v-model="queryParams.approvalState" placeholder="请选择">
					<el-option v-for="dict in dict.type.default_approve" :key="dict.value" :label="dict.label"
						:value="dict.value"> </el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="设备名称" prop="deviceName">
				<el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="设备型号" prop="deviceModel">
				<el-input v-model="queryParams.deviceModel" placeholder="请输入设备型号" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="设备编号" prop="deviceNumber">
				<el-input v-model="queryParams.deviceNumber" placeholder="请输入设备编号" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="设备类型" prop="deviceTypeName">
				<el-input v-model="queryParams.deviceTypeName" placeholder="请输入设备类型" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
					v-hasPermi="['plan:maintain:add']">制定计划</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-circle-check" size="mini" @click="handleSubmits"
					v-hasPermi="['plan:maintain:submit']">提交</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-edit" size="mini" @click="handleApprove({})"
					v-hasPermi="['plan:maintain:approve']">审批</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
					v-hasPermi="['plan:maintain:export']">导出</el-button>
			</el-col>
			<CreateForm :ids="ids" formtype="t_maintenance_schedule" />
			<right-toolbar @changeTableData="changeTableData" menuNames="maintain23" :showSearch.sync="showSearch"
				@queryTable="handleQuery" :columns.sync="columns"
				perm="TMaintenanceSchedule:TMaintenanceSchedule:list"></right-toolbar>
		</el-row>
		<!--   -->
		<div :class="sidebar.opened && eleTabTop <= 85 ? 'eleTab' : !sidebar.opened && eleTabTop <= 85 ? 'eleTabs' : ''"
			class="informationTab" ref="eleTab">
			<el-table :row-class-name="row_class_name" @mousedown.native="mousedownTable" @row-click="row_click"
				@cell-mouse-enter="cell_mouse_enter" @cell-mouse-leave="cell_mouse_leave" @mouseup.native="mouseupTable"
				@mouseleave.native="mouseupTable" ref="table" v-loading="loading" :data="MaintainList"
				@selection-change="handleSelectionChange" row-key="id" lazy :load="loadListDes"
				:tree-props="{ children: 'children', hasChildren: 'hasChildren' }" border height="100%">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="序号" align="center" type="index" width="55">
					           <template slot-scope="scope">

						<div>{{ scope.row.sort }}</div>
						           
					</template>

				</el-table-column>

				<el-table-column label="计划名称" prop="scheduleName" min-width="250" :show-overflow-tooltip="true"
					v-if="columns[0].visible" />
				<el-table-column label="计划编号" prop="scheduleNumber" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[1].visible" />
				<el-table-column label="审批状态" prop="approvalStateName" min-width="150" align="center"
					:show-overflow-tooltip="true" v-if="columns[2].visible">
					<template slot-scope="scope">
						<!-- <div @click="showApproveList(scope.row)">{{ scope.row.approvalStateName }}</div> -->
						<el-tag type="info" v-if="scope.row.approvalState === '0'" class="disableClick">未提交</el-tag>
						<el-tag v-if="scope.row.approvalState === '1'" @click="showApproveList(scope.row)"
							class="clickable">审批中</el-tag>
						<el-tag type="success" v-if="scope.row.approvalState === '2'"
							@click="showApproveList(scope.row)" class="clickable">已通过</el-tag>
						<el-tag type="danger" v-if="scope.row.approvalState === '3'" @click="showApproveList(scope.row)"
							class="clickable">未通过</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="设备名称" prop="deviceName" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[3].visible" />
				<el-table-column label="设备型号" prop="deviceModel" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[4].visible" />
				<el-table-column label="设备编号" prop="deviceNumber" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[5].visible" />
				<el-table-column label="设备类型" prop="deviceTypeName" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[6].visible" />
				<el-table-column label="设置保养人" align="center" prop="userStateName" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[7].visible" />
				<el-table-column label="操作" class-name="small-padding fixed-width" width="240px" fixed="right">
					<template slot-scope="scope">
						<section v-if="scope.row.hasChildren">
							<!-- 待提交和驳回显示 -->
							<el-button size="mini" type="text" icon="el-icon-circle-check"
								@click="handleSubmit(scope.row)"
								v-if="scope.row.approvalState == '0' || scope.row.approvalState == '3'"
								v-hasPermi="['plan:maintain:submit']">提交</el-button>
							<!-- 审批中显示 -->
							<el-button size="mini" type="text" icon="el-icon-edit" @click="handleApprove(scope.row)"
								v-if="scope.row.approvalState == '1' && scope.row.userApprovalStatus == '0'"
								v-hasPermi="['plan:maintain:approve']">审批</el-button>
							<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
								v-hasPermi="['plan:maintain:remove']">删除</el-button>
							<el-button size="mini" type="text" icon="el-icon-wallet" @click="handleAnnex(scope.row)"
								v-hasPermi="['plan:maintain:annex']">附件</el-button>
							<el-button type="text" icon="el-icon-document-copy" size="mini"
								@click="handleCopy(scope.row)" v-hasPermi="['plan:maintain:copy']">复制</el-button>
						</section>
						<section v-else>
							<el-button size="mini" type="text" icon="el-icon-edit" @click="handleDetail(scope.row)"
								v-hasPermi="['plan:maintain:detail']">详情</el-button>
							<el-button size="mini" type="text" icon="el-icon-delete"
								@click="handleDeleteChild(scope.row)"
								v-hasPermi="['plan:maintain:cremove']">删除</el-button>
							<el-button size="mini" type="text" icon="el-icon-guide" @click="handleChange(scope.row)"
								v-hasPermi="['plan:maintain:change']">修改保养计划</el-button>
						</section>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<pagination menuNames="Pagination27" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 制定计划对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body v-dialogDrag
			:before-close="handleClose">
			<el-form ref="form" :model="form" :rules="rules" label-width="80px" class="add-form2">
				<el-form-item label="计划名称" prop="scheduleName">
					<el-input v-model="form.scheduleName" placeholder="请输入计划名称" maxlength="20" show-word-limit />
				</el-form-item>
				<el-form-item label="计划编号" prop="scheduleNumber">
					<el-input v-model="form.scheduleNumber" disabled />
				</el-form-item>
				<div class="planQueryBox">
					<el-form-item size="small" label="设备名称" prop="deviceName">
						<el-input v-model="planParams.deviceName" placeholder="请输入设备名称" maxlength="20" show-word-limit
							clearable />
					</el-form-item>
					<el-form-item size="small" label="设备编号" prop="deviceNumber">
						<el-input v-model="planParams.deviceNumber" placeholder="请输入设备编号" maxlength="20" show-word-limit
							clearable />
					</el-form-item>
					<el-form-item size="small" label="设备型号" prop="deviceModel" style="margin-bottom: 0">
						<el-input v-model="planParams.deviceModel" placeholder="请输入设备型号" maxlength="20" show-word-limit
							clearable />
					</el-form-item>
					<el-form-item label="设备类型" prop="deviceTypeId">
						<el-select v-model="planParams.deviceTypeId" placeholder="请选择" style="width: 255px">
							<el-option v-for="item in deviceTypeList" :key="item.id" :label="item.deviceType"
								:value="item.id">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item style="margin-bottom: 0">
						<el-button type="primary" icon="el-icon-search" size="mini"
							@click="handlePlanQuery">搜索</el-button>
						<el-button icon="el-icon-refresh" size="mini" @click="resetPlanQuery">重置</el-button>
					</el-form-item>
				</div>
				<!-- 设备列表 -->
				<div class="tablebox" style="width: 100%">
					<el-table :data="deviceList" ref="multiselectTable" border @select="handleDeviceSelectionChange"
						@select-all="handleDeviceAllChange">
						<el-table-column type="selection" width="55" align="center" />
						<el-table-column label="序号" align="center" type="index" width="55" />
						<el-table-column prop="deviceTypeName" label="设备类型" min-width="150" align="center"
							:show-overflow-tooltip="true"> </el-table-column>
						<el-table-column prop="deviceNumber" label="设备编号" min-width="150" align="center"
							:show-overflow-tooltip="true"> </el-table-column>
						<el-table-column prop="deviceName" label="设备名称" min-width="150" :show-overflow-tooltip="true">
						</el-table-column>
						<el-table-column prop="deviceModel" label="设备型号" min-width="150" align="center"
							:show-overflow-tooltip="true"> </el-table-column>
						<el-table-column prop="createTime" label="生产日期" min-width="150" align="center"
							:show-overflow-tooltip="true">
							<template slot-scope="scope">
								<span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="purchaseTime" label="购置日期" min-width="150" align="center"
							:show-overflow-tooltip="true">
							<template slot-scope="scope">
								<span>{{ parseTime(scope.row.purchaseTime, "{y}-{m}-{d}") }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="intactState" label="完好状态" min-width="150" align="center"
							:show-overflow-tooltip="true">
							<template slot-scope="scope">
								<dict-tag :options="dict.type.product_intact_state" :value="scope.row.intactState" />
							</template>
						</el-table-column>
						<el-table-column prop="placeStorage" label="安装/存放位置" min-width="150"
							:show-overflow-tooltip="true">
						</el-table-column>
						<el-table-column prop="manufacturingPlant" label="生产厂及国别" min-width="150"
							:show-overflow-tooltip="true">
						</el-table-column>
						<el-table-column prop="cost" label="价值" min-width="150" align="center"
							:show-overflow-tooltip="true">
						</el-table-column>
					</el-table>
					<pagination v-show="planTotal > 0" :total="planTotal" :page.sync="planParams.pageNum"
						:limit.sync="planParams.pageSize" @pagination="getMaintainEquipmentListAct" />
				</div>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
		<!-- 修改保养状态 -->
		<el-dialog :title="changeTitle" :visible.sync="changeOpen" width="900px" append-to-body v-dialogDrag>
			<el-form ref="changeForm" :model="changeForm" label-width="80px" class="add-form2">
				<el-form-item label="计划名称" prop="scheduleName">
					<el-input v-model="changeForm.scheduleName" disabled />
				</el-form-item>
				<el-form-item label="计划编号" prop="scheduleNumber">
					<el-input v-model="changeForm.scheduleNumber" disabled />
				</el-form-item>
				<el-form-item label="设备名称" prop="deviceName">
					<el-input v-model="changeForm.deviceName" disabled />
				</el-form-item>
				<el-form-item label="设备编号" prop="deviceNumber">
					<el-input v-model="changeForm.deviceNumber" disabled />
				</el-form-item>
				<el-form-item label="型号规格" prop="deviceModel">
					<el-input v-model="changeForm.deviceModel" disabled />
				</el-form-item>
				<el-form-item label="设备类型" prop="deviceTypeName">
					<el-input v-model="changeForm.deviceTypeName" disabled />
				</el-form-item>
				<MonthLevel :ruleMonths="ruleMonths" :disabled="changeDisabled" />
			</el-form>
			<div slot="footer" class="dialog-footer" v-if="!changeDisabled">
				<el-button type="primary" @click="submitFormChange">确 定</el-button>
				<el-button @click="cancelChange">取 消</el-button>
			</div>
		</el-dialog>
		<!-- 审批弹框 -->
		<el-dialog title="审批" :visible.sync="openApprove" width="900px" append-to-body v-dialogDrag>
			<ApproveTemplete @cancelApprove="cancelApprove" :openApprove="openApprove"></ApproveTemplete>
		</el-dialog>
		<!-- 审批流程弹框 -->
		<el-dialog title="审批流程" :visible.sync="openRecords" width="900px" append-to-body v-dialogDrag>
			<RecordsTemplete :approveRecord="approveRecord"></RecordsTemplete>
		</el-dialog>
		<!-- 复制计划弹框 -->
		<el-dialog title="复制保养计划" :visible.sync="openCopy" width="900px" append-to-body v-dialogDrag>
			<el-form ref="copyForm" :model="copyForm" label-width="80px" class="add-form1" :rules="copyRules">
				<el-form-item label="计划名称" prop="scheduleName">
					<el-input v-model="copyForm.scheduleName" />
				</el-form-item>
				<el-form-item label="计划编号" prop="scheduleNumber">
					<el-input v-model="copyForm.scheduleNumber" disabled />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitFormCopy">确 定</el-button>
				<el-button @click="cancelCopy">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { getDeviceTypeList, getcolumn } from "@/api/selectList"
import { listMaintain, listMaintainChild, submitMaintain, getMaintainNumber, getMaintainEquipmentList, getMaintain, delMaintain, addMaintain, updateMaintain, delMaintainChild, getRuleMonth, submitMaintainChange, maintainApprove, copyMaintain } from "@/api/plan/maintain"
import MonthLevel from "./MonthLevel"
import ApproveTemplete from "@/views/components/ApproveTemplete"
import RecordsTemplete from "@/views/components/RecordsTemplete"
import { approvalRecord } from "@/api/productTechnology/productTechnologyVersions"
import CreateForm from "@/views/components/CreateForm"
import { mapGetters } from "vuex"
import searchStateMixin from '@/layout/mixin/searchStateMixin.js'
import DocumentShow from "@/views/components/DocumentShow"
export default {
	name: "Maintain",
	dicts: ["default_approve", "product_intact_state"],
	mixins: [searchStateMixin],
	computed: {
		...mapGetters(["sidebar"])
	},
	components: { MonthLevel, ApproveTemplete, RecordsTemplete, CreateForm, DocumentShow },
	data() {
		return {
			isMousedownTable: false, //是否按下表格
			currentEnterRow: null, //当前移入的行数据
			// 设备类型列表
			deviceTypeList: [],
			fileVedioList: [],
			showfileListDialog: false,
			showTodoListDialog: false,
			eleTabTop: 0, //表格容器距浏览器顶部距离
			testval: undefined,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 设备保养计划表格数据
			MaintainList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				scheduleName: undefined,
				approvalState: undefined,
				deviceName: undefined,
				deviceModel: undefined,
				deviceNumber: undefined,
				deviceTypeName: undefined
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				scheduleName: [{ required: true, message: "请输入计划名称", trigger: "blur" }]
			},
			deviceList: [],
			// 修改保养计划弹框
			changeOpen: false,
			changeTitle: "",
			changeForm: {},
			ruleMonths: [],
			changeDisabled: false,
			// 更新树刷新
			treeMap: new Map(),
			// 审批数据
			openApprove: false,
			approveRow: undefined,
			// 审批流程
			openRecords: false,
			approveRecord: [],
			// 复制弹框
			openCopy: false,
			copyForm: {},
			copyRules: {
				scheduleName: [{ required: true, message: "请输入计划名称", trigger: "blur" }]
			},
			treetablekey: Math.random(),
			// 列信息
			columns: [
				{ key: 0, label: `计划名称`, visible: true },
				{ key: 1, label: `计划编号`, visible: true },
				{ key: 2, label: `审批状态`, visible: true },
				{ key: 3, label: `设备名称`, visible: true },
				{ key: 4, label: `设备型号`, visible: true },
				{ key: 5, label: `设备编号`, visible: true },
				{ key: 6, label: `设备类型`, visible: true },
				{ key: 7, label: `设置保养人`, visible: true }
			],
			planTotal: 0,
			planParams: {
				pageNum: 1,
				pageSize: 10,
				deviceName: undefined,
				deviceNumber: undefined,
				deviceModel: undefined
			},
			//制定计划弹窗多选id
			deviceIds: [],
			rows: []
		}
	},
	created() {
		// this.getSize()
		// 如果是页面刷新，重置查询
		if (window.performance && performance.navigation.type === performance.navigation.TYPE_RELOAD) {
			// 清除URL中的查询参数（不刷新页面）
			this.resetForm("queryForm")
			window.history.replaceState({}, document.title, window.location.pathname)
		}
	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
	},
	watch: {
		"$route.query": {
			handler(newQuery, oldQuery) {
				if (newQuery.queryData) {
					if (Object.keys(newQuery.queryData).length === 0) {
						this.resetQuerys()
						// this.getSize()
					} else {
						this.queryParams = { ...this.queryParams, ...JSON.parse(newQuery.queryData) }
						// this.getSize()
					}
				} this.getSize()
			},
			immediate: true, // 立即执行一次
			deep: true // 深度监听
		}
	},
	activated() {
		// this.getSize()
		//获取表格容器距页面头部的距离
		this.handleScrollx()
	},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},
	methods: {
		getSize() {
			getcolumn({ pageName: "Pagination27" }).then(response => {
				this.queryParams.pageSize = response.data.length ? (response.data[0].limit ? response.data[0].limit : 10) : 10
				this.getList()
			})
		},
		// 查询设备类型列表
		async getDeviceTypeList() {
			let ret = await getDeviceTypeList()
			if (ret && ret.code == 200) {
				this.deviceTypeList = ret.rows
			}
		},
		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		/** 查询设备保养计划列表 */
		getList() {
			this.loading = true
			listMaintain(this.queryParams).then(response => {
				this.MaintainList = response.rows
				this.MaintainList.forEach((item, index) => {
					item.hasChildren = true
					item.sort = index + 1
					this.$refs.table.toggleRowExpansion(item, false)
				})
				this.total = response.total
				this.loading = false
			})
		},
		// 获取列表详情
		async loadListDes(tree, treeNode, resolve) {
			if (!this.treeMap.has(tree.id)) {
				this.treeMap.set(tree.id, {
					treeNode,
					resolve
				})
			}
			let queryParams = JSON.parse(JSON.stringify(this.queryParams))
			delete queryParams.pageSize
			delete queryParams.pageNum
			let data = {
				id: tree.id,
				...queryParams
			}
			let ret = await listMaintainChild(data)
			ret.rows.forEach((item, index) => {
				// 父子id会冲突
				item.id = "c" + item.id
				item.sort = index + 1
			})
			resolve(ret.rows)
		},
		// 取消按钮
		cancel() {
			this.open = false
			this.$refs.table.clearSelection()
			this.reset()

			//清空勾选和已经选中的id
			this.$refs.multiselectTable.clearSelection()
			this.deviceIds = []
		},
		// 表单重置
		reset() {
			this.form = {
				id: undefined,
				scheduleNumber: undefined,
				scheduleName: undefined
			}
			this.resetForm("form")
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			this.saveSearchState()
			this.getList()
			this.treetablekey = Math.random()
		},
		/** 重置按钮操作 */
		resetQuerys() {
			this.resetForm("queryForm")
			this.queryParams = {
				pageNum: 1,
				pageSize: this.queryParams.pageSize,
				scheduleName: undefined,
				approvalState: undefined,
				deviceName: undefined,
				deviceModel: undefined,
				deviceNumber: undefined,
				deviceTypeName: undefined
			}
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm")
			this.queryParams = {
				pageNum: 1,
				pageSize: this.queryParams.pageSize,
				scheduleName: undefined,
				approvalState: undefined,
				deviceName: undefined,
				deviceModel: undefined,
				deviceNumber: undefined,
				deviceTypeName: undefined
			},
				this.clearSearchCache()
			this.handleQuery()
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.rows = selection
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		// 表格按下
		mousedownTable(event) {
			const target = event.target
			// 判断target的class属性确定是否点击在复选框上
			if (target.classList.contains("el-checkbox__inner")) {
				this.currentEnterRow && this.$refs.table.toggleRowSelection(this.currentEnterRow)
				this.isMousedownTable = true
			}
		},
		// 单击表格行
		row_click(row, column, event) {
			// this.currentEnterRow || this.$refs.table.toggleRowSelection(row)
			if (column && column.label == "操作") {
				return
			} else {
				this.$refs.table.toggleRowSelection(row)
			}
		},
		changeTableData() {
			this.$nextTick(() => {
				this.$refs.table.doLayout()
			})
		},

		// 进入单元格
		cell_mouse_enter(row, column, cell, event) {
			this.isMousedownTable && this.$refs.table.toggleRowSelection(row)
			this.currentEnterRow = row
		},
		// 离开单元格
		cell_mouse_leave(row, column, cell, event) {
			this.currentEnterRow = null
		},
		// 鼠标弹起或者离开表格
		mouseupTable(d) {
			this.isMousedownTable = false
		},
		// 表格每行样式
		row_class_name({ row, rowIndex }) {
			return this.rows.find(v => v.id == row.id) ? "selected" : ""
		},
		// 设备多选事件
		handleDeviceSelectionChange(selection, row) {
			if (!this.deviceIds.includes(row.id)) {
				this.deviceIds.push(row.id)
			} else {
				this.deviceIds.forEach((id, index) => {
					if (id === row.id) {
						this.deviceIds.splice(index, 1)
					}
				})
			}
		},
		// 设备全选事件
		handleDeviceAllChange(selection) {
			if (selection.length > 0) {
				selection.forEach(item => {
					if (!this.deviceIds.includes(item.id)) {
						this.deviceIds.push(item.id)
					}
				})
			} else {
				this.deviceList.forEach(item => {
					this.deviceIds.forEach((id, index) => {
						if (id === item.id) {
							this.deviceIds.splice(index, 1)
						}
					})
				})
			}
		},
		handleClose(down) {
			this.$refs.multiselectTable.clearSelection()
			down()
		},
		/** 新增按钮操作 */
		async handleAdd() {
			this.reset()
			// 获取保养编号和设备列表
			let ret = await getMaintainNumber()
			if (ret.code == 200) {
				this.form.scheduleNumber = ret.msg
			}
			this.open = true
			this.title = "制定设备保养计划"
			this.getDeviceTypeList()
			this.planParams.pageNum = 1
			this.deviceIds = []
			this.$nextTick(() => {
				this.$refs.multiselectTable.clearSelection()
				this.getMaintainEquipmentListAct()
			})
		},
		// 设备列表检索
		async getMaintainEquipmentListAct() {
			let res = await getMaintainEquipmentList(this.planParams)
			if (res.code == 200) {
				this.deviceList = res.rows
				this.planTotal = res.total
				this.$nextTick(() => {
					this.deviceList.forEach(item => {
						if (this.deviceIds.includes(item.id)) {
							this.$refs.multiselectTable.toggleRowSelection(item, true)
						}
					})
				})
			}
		},
		handlePlanQuery() {
			this.planParams.pageNum = 1
			this.getMaintainEquipmentListAct()
		},
		resetPlanQuery() {
			this.planParams = {
				pageNum: 1,
				pageSize: 10,
				deviceName: undefined,
				deviceNumber: undefined,
				deviceModel: undefined
			}
			this.handlePlanQuery()
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset()
			const id = row.id || this.ids
			getMaintain(id).then(response => {
				this.form = response.data
				this.open = true
				this.title = "修改设备保养计划"
			})
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					if (this.form.id != undefined) {
						updateMaintain(this.form).then(response => {
							this.$modal.msgSuccess("修改成功")
							this.open = false
							this.$refs.table.clearSelection()
							this.getList()
						})
					} else {
						const params = {
							...this.form,
							deviceIds: this.deviceIds
						}
						addMaintain(params).then(response => {
							this.$modal.msgSuccess("新增成功")
							this.open = false
							this.$refs.table.clearSelection()
							this.getList()
							this.deviceIds = []
						})
					}
				}
			})
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const ids = row.id || this.ids
			this.$modal
				.confirm("是否确认删除数据项？")
				.then(function () {
					return delMaintain(ids)
				})
				.then(() => {
					this.getList()
					this.$modal.msgSuccess("删除成功")
				})
				.catch(() => { })
		},
		handleSubmits() {
			let checkp = this.rows.every(item => {
				return typeof item.id == "number"
			})
			if (!checkp) {
				this.$modal.msg("只能选择父级产品进行提交")
				return false
			}
			const _this = this
			this.$modal
				.confirm(`是否确认提交数据？`)
				.then(function () {
					return submitMaintain({
						workIds: _this.ids,
						workflowType: "1"
					})
				})
				.then(() => {
					_this.getList()
					localStorage.setItem("todoMessage", "maintains1")
					_this.$modal.msgSuccess("提交成功")
					_this.$refs.table.clearSelection()
				})
				.catch(() => { })
		},
		// 列表父级提交
		handleSubmit(row) {
			this.$modal
				.confirm("是否确认提交数据项？")
				.then(function () {
					let data = {
						workId: row.id,
						workflowType: "1",
						// 1是提交，3是重复提交
						submitStatus: row.approvalState == "0" ? "1" : "2"
					}
					return submitMaintain(data)
				})
				.then(() => {
					this.getList()
					localStorage.setItem("todoMessage", "maintains2")
					this.$modal.msgSuccess("操作成功")
				})
				.catch(() => { })
		},
		// 子列表删除
		handleDeleteChild(row) {
			const id = row.id.replace("c", "")
			this.$modal
				.confirm("是否确认删除数据项？")
				.then(function () {
					return delMaintainChild(id)
				})
				.then(() => {
					let treeObj = this.treeMap.get(row.maintenanceScheduleId)
					this.loadListDes({ id: row.maintenanceScheduleId }, treeObj.treeNode, treeObj.resolve)
					this.$modal.msgSuccess("删除成功")
				})
				.catch(error => {
					console.log(error)
				})
			return
		},
		// 更改保养计划
		async handleChange(row) {
			this.changeDisabled = false
			this.changeOpen = true
			this.changeTitle = "修改保养计划"
			let id = row.id.replace("c", "")
			let ret = await getRuleMonth(id)
			let ruleMonths = [
				{ month: "1", monthName: "一月", maintenanceLevelId: undefined },
				{ month: "2", monthName: "二月", maintenanceLevelId: undefined },
				{ month: "3", monthName: "三月", maintenanceLevelId: undefined },
				{ month: "4", monthName: "四月", maintenanceLevelId: undefined },
				{ month: "5", monthName: "五月", maintenanceLevelId: undefined },
				{ month: "6", monthName: "六月", maintenanceLevelId: undefined },
				{ month: "7", monthName: "七月", maintenanceLevelId: undefined },
				{ month: "8", monthName: "八月", maintenanceLevelId: undefined },
				{ month: "9", monthName: "九月", maintenanceLevelId: undefined },
				{ month: "10", monthName: "十月", maintenanceLevelId: undefined },
				{ month: "11", monthName: "十一月", maintenanceLevelId: undefined },
				{ month: "12", monthName: "十二月", maintenanceLevelId: undefined }
			]
			ret.data.planCalendarVoList.forEach(item => {
				ruleMonths.forEach((item1, index1) => {
					if (item.month == item1.month) {
						item1.id = item.id
						item1.maintenanceLevelId = item.maintenanceLevelId
						item1.maintenanceUserId = item.maintenanceUserId
						item1.maintenanceLevel = item.maintenanceLevel
						item1.maintenanceUser = item.maintenanceUser
					}
				})
			})
			this.ruleMonths = ruleMonths
			this.changeForm = ret.data
			this.changeForm["id"] = id
			this.changeForm.maintenanceScheduleId = row.maintenanceScheduleId
		},
		// 详情
		handleDetail(row) {
			this.handleChange(row)
			this.changeDisabled = true
		},
		// 更改保养计划
		submitFormChange() {
			if (this.changeDisabled) {
				this.changeOpen = false
				return false
			}
			// 判断有级别的是否都有保养人
			let check = this.ruleMonths.find(item => {
				return item.maintenanceLevelId && !item.maintenanceUserId
			})
			if (check) {
				this.$modal.msg("请选择保养人")
				return false
			}
			let data = {
				id: this.changeForm.id,
				planCalendarVoList: this.ruleMonths
			}
			submitMaintainChange(data).then(response => {
				this.$modal.msgSuccess("修改成功")
				this.changeOpen = false
				let treeObj = this.treeMap.get(this.changeForm.maintenanceScheduleId)
				this.loadListDes({ id: this.changeForm.maintenanceScheduleId }, treeObj.treeNode, treeObj.resolve)
			})
		},
		// 审批
		handleApprove(row) {
			this.approveRow = row
			if (!row.id) {
				let checkp = this.rows.every(item => {
					return typeof item.id == "number"
				})
				if (!checkp) {
					this.$modal.msg("只能选择父级产品进行审批")
					return false
				}
			}
			this.openApprove = true
		},

		// 审批取消
		async cancelApprove(ret) {
			if (!ret.flag) {
				this.openApprove = false
				return false
			}
			let data = {
				approvalStatus: ret.approvalStatus,
				causeRejection: ret.causeRejection,
				workflowType: "1"
			}
			console.log(this.approveRow)
			this.approveRow.id ? (data.id = this.approveRow.id) : (data.ids = this.ids)
			let res = await maintainApprove(data)
			if (res.code == 200) {
				this.$modal.msgSuccess("操作成功")
				localStorage.setItem("todoMessage", "maintains3")
				this.getList()
				this.$refs.table.clearSelection()
			}
			this.openApprove = false
		},
		// 关闭更改保养计划
		cancelChange() {
			this.changeOpen = false
		},
		// 附件
		handleAnnex(row) {
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: row.id,
					typeId: 9,
					perm: "plan:maintain:annex",
					// queryParams: JSON.stringify(this.queryParams),
					paths: "/plan/maintain",
				}
			})
		},
		/** 导出按钮操作 */
		handleExport() {
			this.download(
				"/TMaintenanceSchedule/TMaintenanceSchedule/export",
				{
					...this.queryParams
				},
				`Maintain_${new Date().getTime()}.xlsx`
			)
		},
		// 获取审批详情
		showApproveList(row) {
			if (row.approvalStatus == "0") {
				return false
			}
			this.openRecords = true
			approvalRecord({
				id: row.id,
				workflowType: "1"
			}).then(res => {
				this.openRecords = true
				this.approveRecord = res.data
			})
		},
		// 复制保养计划
		async handleCopy(row) {
			this.copyForm = {
				id: undefined,
				scheduleNumber: undefined,
				scheduleName: undefined
			}
			this.resetForm("copyForm")
			this.openCopy = true
			this.copyForm.id = row.id
			// 获取编号
			let ret = await getMaintainNumber()
			if (ret.code == 200) {
				this.copyForm.scheduleNumber = ret.msg
			}
		},
		// 提交复制数据
		submitFormCopy() {
			this.$refs["copyForm"].validate(valid => {
				if (valid) {
					copyMaintain(this.copyForm).then(response => {
						this.$modal.msgSuccess("操作成功")
						this.openCopy = false
						this.getList()
					})
				}
			})
		},
		// 取消
		cancelCopy() {
			this.openCopy = false
		}
	}
}
</script>

<style lang="scss" scoped>
/*
// 列表计划名称左对齐，标题居中
::v-deep .el-table__header .el-table__cell {
  text-align: center;
}
*/
</style>
<style lang="scss" scoped>
::v-deep .el-table__fixed-header-wrapper .fixed-width {
	width: 240px !important;
}

.planQueryBox {
	width: 100%;
	display: flex;
	flex-wrap: wrap;
	box-sizing: border-box;
	padding: 16px 10px 10px 10px;
	margin-bottom: 10px;
	border-radius: 8px;
	border: 1px solid #eee;
}
</style>
